<?php

/**
 * Erra_Fields_ComboBox - Main combobox class
 *
 * @package
 * @author Alexis Eric
 * @copyright Copyright (c) 2012 - Erra Prod
 * @version $1.0$
 * @access public
 */
class Erra_Fields_MultiLevelComboBox extends Erra_Fields_Base_Field {

    public function __construct($objectId) {
        parent::__construct($objectId);
        $this->setDatabaseType('varchar', 128);
    }

    /**
     * Erra_Fields_ComboBox::editInstance() - Show a combobox (<select>.<option>val</option></select>) with key=>values set with the (...->fill($assoc_array));
     *
     * @param mixed $lang
     * @return
     */
    public function editInstance(Array $extraProperties = null) {
        $res = '<div class="erra-form-field-instance">';
        $res .= $this->outputFieldHeader();
        $extraProperties['class'] = isset($extraProperties['class']) ? $extraProperties['class'] . ' chzn-select' : ' chzn-select';
        $res .= '<select ' . $this->getHtmlAttributes($extraProperties) . ' name="' . $this->getHtmlName() . '" id="' . $this->getHtmlId() . '">';

        if (isset($this->fieldData[0])) {
            $fieldData = $this->fieldData[0]['children'];
            foreach ($fieldData as $optionKey => $optionValue) {
                if (is_array($optionValue['children'])) {
                    $res .= '<optgroup label="' . $optionValue['title'] . '">';
                    foreach ($optionValue['children'] as $optionKey => $optionValue) {
                        $selected_flag = (!is_null($this->_rawData) && $this->_rawData == $optionValue['key']) ? ' selected ' : '';
                        $res .= '<option ' . $selected_flag . ' value="' . $optionValue['key'] . '">' . $optionValue['title'] . '</option>';
                    }
                    $res .= '</optgroup>';
                } else {
                    $selected_flag = (!is_null($this->_rawData) && $this->_rawData == $optionValue['key']) ? ' selected ' : '';
                    $res .= '<option ' . $selected_flag . ' value="' . $optionValue['key'] . '">' . $optionValue['title'] . '</option>';
                }
            }
        }
        $res .= '</select>';
        $res .= '</div>';
        return $res;
    }

    function toHtml($displayParameters = null) {
        if (isset($this->fieldData) && is_array($this->fieldData) && isset($this->fieldData[$this->getRawData()])) {
            return $this->fieldData[$this->getRawData()];
        }
        return $this->getRawData();
    }

}